package com.vendar.quicknote;

import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;

import com.vendar.quicknote.R;
import com.vendar.oauth.OAuthSinaWeibo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/*
 * tweet weibo activity.
 * input args:
 * 1. oauth userinfo: userid,access token,access secret
 * 2. tweet content, may be empty
 */
public class TweetWeiboActivity extends Activity implements OnClickListener{
	private Weibo mWeibo = null;
	private String mContent = null;
	
	private Button mTweetBtn = null;
	private EditText mEditor = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.send_weibo);
		Setup();
	}
	
	private void Setup(){
		mTweetBtn = (Button)findViewById(R.id.tweetBtn);
		mTweetBtn.setOnClickListener(this);
		mEditor = (EditText)findViewById(R.id.weiboEditor);
		
        Bundle extras = getIntent().getExtras();
    	mContent = extras.getString("content");
    	mEditor.setText(mContent);
    	
    	//TODO check the validity
		mWeibo = new Weibo();
		mWeibo.setOAuthConsumer(OAuthSinaWeibo.APP_KEY, OAuthSinaWeibo.APP_SECRET);
		mWeibo.setUserId(extras.getString("user_id"));
		mWeibo.setOAuthAccessToken(extras.getString("access_token"),
				extras.getString("access_secret"));
	}
	
	@Override
	public void onClick(View v) {
		if(v == mTweetBtn){
			//tweet
			try {
				mContent = mEditor.getText().toString();
				if( mWeibo != null ) mWeibo.updateStatus(mContent);
			} catch (WeiboException e) {
				Toast.makeText(this, getResources().getString(R.string.tweet_failed), 100).show();
				this.setResult(RESULT_CANCELED);
				this.finish();
				return ;
			}
			Toast.makeText(this, getResources().getString(R.string.tweet_succeed), 100).show();
		}
		Intent intent = new Intent();
		intent.setClass(TweetWeiboActivity.this, StartActivity.class);
		Bundle extras = new Bundle();
		extras.putString("content", this.mContent);
		intent.putExtras(extras);
		this.setResult(RESULT_OK, intent);
		this.finish();
	}
}
